<!--
 * @Author: wuzhen
 * @Date: 2020-01-14 15:16:39
 * @LastEditors: wuzhen
 * @LastEditTime: 2020-04-18 14:46:41
 * @Description: 头部注释
 -->
<template>
  <div class="chat-sider">
    <div class="search-input">
      <!-- 搜索ID/手机号/昵称 -->
      <Input
        :search="true"
        @on-search="onSearch"
        @on-change="onChange"
        :placeholder="$t('placeholder_book')"
      />
    </div>
    <div
      class="ivu-spin"
      style="display:flex;width: 100%;height:100px;align-items: center;justify-content: center"
      v-if="loading"
    >
      <div class="load-3">
        <div class="line"></div>
        <div class="line"></div>
        <div class="line"></div>
      </div>
    </div>
    <div class="user-scroll-bar" v-else>
      <div class="user-list">
        <template v-for="(item, key) in dataList">
          <div :key="key + 10000" class="friend" v-if="item.data.length">
            <h3>{{ item.letter }}</h3>
            <div
              class="user-item flex"
              :class="{ active: currentId === child.id }"
              v-for="child in item.data"
              :key="child.id"
              @contextmenu.prevent="openMenu(child, $event)"
              @click="onClick(child)"
            >
              <div class="user-img">
                <img
                  :src="require('@/assets/image/icon_group.png')"
                  v-if="child.msgkind === 30 && child.grouptype === 20"
                />
                <wz-img
                  :type="child.msgkind === 30 ? 'group' : 'face'"
                  :src="child.face"
                  v-else
                />
              </div>
              <div class="flex-item" style="overflow:hidden">
                <p class="user-name">{{ child.name }}</p>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <context-menu
      :context-menu="contextMenu"
      :left="contextLeft"
      :top="contextTop"
      @on-close="onCloseContextMenu"
      @on-click="onClickContextMenu"
      v-if="showContextMenu"
    ></context-menu>
    <Modal v-model="deleteModal" width="380">
      <p slot="header" style="color:#f60;text-align:center">
        <span> {{ $t("btn_delFriends") }} </span>
      </p>
      <div style="text-align:center">
        <p>{{ $t("ok_delFriends") }}</p>
      </div>
      <div
        class="flex modal-ft"
        slot="footer"
        style="padding: 0 15px 15px 15px"
      >
        <div class="flex-item" style="padding: 0 15px">
          <Button type="primary" long @click="onDelete">{{
            $t("btn_confirm")
          }}</Button>
        </div>
        <div class="flex-item" style="padding: 0 15px">
          <Button type="error" long @click="deleteModal = false">{{
            $t("btn_cancel")
          }}</Button>
        </div>
      </div>
    </Modal>

    <Modal v-model="updateNameModal" width="380">
      <p slot="header" style="text-align:center">
        <span> {{ $t("btn_remarks") }} </span>
      </p>
      <div class="updateFlex">
        <div class="lable">{{ $t("name") }}：</div>
        <div class="input">
          <Input v-model="updateName" :placeholder="$t('placeholder_name')" />
        </div>
      </div>
      <div
        class="flex"
        slot="footer"
        style="padding: 0 15px 15px 15px;justify-content: center;"
      >
        <div style="width:138px">
          <Button type="primary" long @click="upDateMyFiend">{{
            $t("btn_confirm")
          }}</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  Input,
  Badge,
  Avatar,
  Icon,
  Modal,
  Message,
  Button
} from "view-design";
import ContextMenu from "@/components/ContextMenu/index.vue";
import { delFriend, updateFriendname } from "@/request/api";
import { formatLetter } from "@/libs/units";
export default {
  components: {
    Input,
    Badge,
    Avatar,
    Icon,
    Modal,
    Button,
    Message,
    ContextMenu
  },
  data() {
    return {
      currentId: null,
      currentInfo: null,
      groupData: [],
      friendData: [],
      dataList: [],
      showContextMenu: false,
      contextMenu: [
        {
          label: this.$t("btn_send"),
          value: "send"
        },
        {
          label: this.$t("btn_remarks"),
          value: "update"
        },
        {
          label: this.$t("btn_delFriends"),
          value: "delete"
        }
      ],
      contextLeft: 0,
      contextTop: 0,
      loading: true,
      deleteModal: false,
      updateNameModal: false,
      updateName: "",
      modal_loading: false
    };
  },
  created() {
    this.$bus.$on("hideBookSiderPopup", () => {
      this.showContextMenu = false;
    });
    this.getData();
  },
  beforeDestroy() {
    this.$bus.$off("hideBookSiderPopup");
  },
  methods: {
    // 获取数据
    async getData(keyword = "") {
      this.groupData = [];
      this.friendData = [];
      const letter = [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
        "#"
      ];
      let friends = [];
      if (keyword.length === 9 && !isNaN(Number(keyword))) {
        friends = this.friends.filter(v => v.id === Number(keyword));
        this.groupData = this.groups.filter(v => v.id === Number(keyword));
      } else if (keyword.length === 11 && !isNaN(Number(keyword))) {
        friends = this.friends.filter(
          v => Number(v.mobile) === Number(keyword)
        );
        this.groupData = [];
      } else {
        friends = this.friends.filter(v => v.name.includes(keyword));
        this.groupData = this.groups.filter(v => v.name.includes(keyword));
      }
      const data = friends.map(v => {
        return {
          ...v,
          ...{
            letter: letter.find(c => c === v.letter) || "#"
          }
        };
      });
      letter.forEach(v => {
        this.friendData.push({
          letter: v,
          data: data.filter(m => m.letter === v)
        });
      });
      this.dataList = [
        ...[
          {
            letter: this.$t("group_chat"),
            data: this.groupData
          }
        ],
        ...this.friendData
      ];
      this.$nextTick(() => {
        this.loading = false;
      });
      for (let index = 0; index < this.dataList.length; index++) {
        const element = this.dataList[index];
        if (element.data.length) {
          this.currentId = element.data[0].id;
          this.$emit("on-click", element.data[0], element.data[0].type);
          return;
        }
      }
    },
    // 搜索
    onSearch(value) {
      if (!value.trim()) return;
      this.loading = true;
      this.getData(value);
    },
    onChange(e) {
      if (!e.target.value.trim()) {
        this.loading = true;
        this.getData("");
      }
    },
    // 点击群、好友查看详情
    onClick(item) {
      if (this.currentId === item.id) return;
      this.currentId = item.id;
      this.$emit("on-click", item);
    },
    openMenu(item, e) {
      this.currentInfo = item;
      if (item.msgkind === 30) {
        this.contextMenu = [
          {
            label: this.$t("btn_send"),
            value: "send"
          }
        ];
      } else {
        this.contextMenu = [
          {
            label: this.$t("btn_send"),
            value: "send"
          },
          {
            label: this.$t("btn_remarks"),
            value: "update"
          },
          {
            label: this.$t("btn_delFriends"),
            value: "delete"
          }
        ];
      }
      this.contextLeft = e.clientX - this.screen.x;
      this.contextTop = e.clientY - this.screen.y;
      if (this.contextTop > 590 && item.msgkind === 20) {
        this.contextTop = 540;
      }
      this.$emit("close-user-info");
      this.$bus.$emit("hideBarPopup");
      this.showContextMenu = true;
    },
    onCloseContextMenu() {
      this.showContextMenu = false;
    },
    onClickContextMenu(value) {
      this.showContextMenu = false;
      switch (value) {
        case "send":
          this.onSendMsg();
          break;
        case "update":
          this.updateName = this.currentInfo.name;
          this.updateNameModal = true;
          break;
        case "delete":
          this.deleteModal = true;
          break;
        default:
          break;
      }
    },
    // 发消息
    onSendMsg() {
      const obj = {
        id: this.currentInfo.id,
        msgkind: this.currentInfo.msgkind,
        face: this.currentInfo.face,
        name: this.currentInfo.name
      };
      // 修改正在聊天对象
      this.storeChatting(obj);
      // 修改正在聊天成员列表
      this.storeChatUsers(obj);
      // 跳转到聊天页面
      this.$router.push("chat");
    },
    // 删除好友
    async onDelete() {
      try {
        const res = await delFriend({
          friendId: this.currentInfo.id
        });
        if (res.code === 200) {
          const currentIndex = this.friends.findIndex(
            v => v.id === this.currentInfo.id
          );
          this.friends.splice(currentIndex, 1);
          this.set_friends(this.friends);
          this.getData();
          this.deleteModal = false;
          Message.success("删除成功");
          this.getData();
        }
      } catch (e) {
        console.log(e);
        Message.error("删除失败");
      }
    },
    // 修改备注
    async upDateMyFiend() {
      try {
        if (this.updateName === "" || this.updateName.length > 20) {
          Message.warning("名称不能为空且长度小于20字符");
          return;
        }
        const res = await updateFriendname({
          friendId: this.currentInfo.id,
          friendname: this.updateName
        });
        if (res.code === 200) {
          this.friends.forEach(v => {
            if (this.currentInfo.id === v.id) {
              v.name = this.updateName;
              v.letter = formatLetter(this.updateName);
            }
          });
          this.set_friends(this.friends);
          this.getData();
          this.updateNameModal = false;
          Message.success("修改成功");
        }
      } catch (error) {
        console.log(error);
        Message.error("修改失败");
      }
    }
  }
};
</script>
<style lang="less" scoped>
.updateFlex {
  display: flex;
  align-items: center;
  .input {
    flex: 1;
  }
}
</style>
